package com.haoshuang.zhouzhoubang.ui.page.home

import android.Manifest
import android.os.Bundle
import android.widget.TextView
import com.alipay.face.api.ZIMFacade
import com.alipay.face.api.ZIMFacadeBuilder
import com.haoshuang.zhouzhoubang.MyApp
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.config.URLConstants
import com.haoshuang.zhouzhoubang.databinding.FragmentHomeBinding
import com.haoshuang.zhouzhoubang.model.bean.HomeDataBean
import com.haoshuang.zhouzhoubang.model.event.RefreshHomeData
import com.haoshuang.zhouzhoubang.model.event.RefreshTeamUserInfo
import com.haoshuang.zhouzhoubang.ui.activity.AgreementActivity
import com.haoshuang.zhouzhoubang.ui.activity.MemberManagerActivity
import com.haoshuang.zhouzhoubang.ui.activity.TeamBzActivity
import com.haoshuang.zhouzhoubang.ui.dialog.BusinessLicenseDialog
import com.haoshuang.zhouzhoubang.ui.page.data.DataStatisticsActivity
import com.haoshuang.zhouzhoubang.ui.page.help.detail.HelpDetailActivity
import com.haoshuang.zhouzhoubang.ui.page.home.settings.StoreSettingsActivity
import com.haoshuang.zhouzhoubang.ui.page.main.MainActivity
import com.haoshuang.zhouzhoubang.ui.page.mine.wallet.MyWalletActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.background.BackgroundInputInfoActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.collaborationcosts.CollaborationCostsActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.contactbutler.ContactButlerActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.settled.StoreSettledInputActivity
import com.haoshuang.zhouzhoubang.ui.page.settled.upload.UploadBusinessLicenseActivity
import com.haoshuang.zhouzhoubang.utils.PermissionHelper
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.LogUtil
import com.mufeng.libs.utils.ktx.toDateForm
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.load
import com.mufeng.libs.utils.view.visibleOrGone
import com.qw.curtain.lib.Curtain
import com.qw.curtain.lib.CurtainFlow
import com.qw.curtain.lib.flow.CurtainFlowInterface
import com.qw.curtain.lib.shape.RoundShape
import java.util.ArrayList
import java.util.Date


/**
 *
 */
class HomeFragment : BaseVMFragment<HomeViewModel, FragmentHomeBinding>() {

    private var homeData: HomeDataBean? = null

    // 公告列表
    private val noticeList = arrayListOf<HomeDataBean.SystemNotice>()

    companion object {
        fun getInstance(): HomeFragment {
            val fragment = HomeFragment()
            fragment.arguments = Bundle().apply {

            }
            return fragment
        }
    }

    override fun initView(savedInstanceState: Bundle?) {

        // 测试按钮
        binding.tvOpenMaster.visibleOrGone(false)
        binding.tvOpenMaster.clickWithTrigger {
//            MediaPlayUtils.playAudio("submit_order_success.mp3")
        }

        // 打开抽屉
        binding.rivHead.click {
            if (mActivity is MainActivity) {
                (mActivity as MainActivity).showDrawerLayout()
            }
        }

        // 门店入驻状态
        // 联系管家
        binding.tvContactButler.click {
            startPage<ContactButlerActivity>()
        }

        // 点击统计
        binding.llStatistics.clickWithTrigger {
            if (homeData?.status != "8") {
                return@clickWithTrigger
            }
            startPage<DataStatisticsActivity>()
        }

        // 点击待接单
        binding.llPendingOrders.clickWithTrigger {
            (mActivity as MainActivity).startOrderPage(0)
        }
        // 待服务
        binding.llUnserviced.clickWithTrigger {
            (mActivity as MainActivity).startOrderPage(1)
        }
        // 进行中
        binding.llInProgress.clickWithTrigger {
            (mActivity as MainActivity).startOrderPage(2)
        }
        // 返工单
        binding.llReturnOrder.clickWithTrigger {
            (mActivity as MainActivity).startOrderPage(4)
        }
        // 退款售后
        binding.llAfterSales.clickWithTrigger {
            (mActivity as MainActivity).startOrderPage(5)
        }

        // 门店入驻
        binding.tvConfirm.click {
            when (homeData?.status) {
                "-1" -> {
                    // 未入驻 去入驻
                    startPage<StoreSettledInputActivity>()
                }

                "0" -> {
                    // 待审核 联系管家
                    startPage<ContactButlerActivity>()
                }

                "2" -> {
                    // 审核未通过 重新认证
                    startPage<StoreSettledInputActivity>()
                }

                "3" -> {
                    // 未人脸 去认证
//                    startPage<FaceRecognitionActivity>()
                    PermissionHelper.requestPermission(
                        mActivity,
                        "权限使用说明",
                        "用于帮您实现实名认证, 人脸识别",
                        Manifest.permission.CAMERA,
                    ) {

                        if (it) {
                            val metaInfos = ZIMFacade.getMetaInfos(mActivity)
                            val name = AccountUtils.user?.user_name
                            val idNumber = AccountUtils.user?.id_card
                            vm.getFaceParams(name, idNumber, metaInfos)
                        } else {
                            toast("请开启相机权限")
                        }
                    }
                }

                "5" -> {
                    // 未签署合同 去签署
                    startPage<AgreementActivity>()
                }

                "7" -> {
                    // 未交费 立即支付
                    startPage<CollaborationCostsActivity>()
                }

                "9" -> {
                    // 后台录入 查看资料
                    startPage<BackgroundInputInfoActivity>()
                }
            }

        }

        binding.marqueeView.setOnItemClickListener { position, textView ->
            val notice = noticeList[position]
            startPage<HelpDetailActivity>(
                "title" to notice.title,
                "url" to "${URLConstants.baseUrl}${notice.detail_url}"
            )
        }

        binding.refreshLayout.setOnRefreshListener {
            isShowing = false
            vm.getHomeData()
        }

        // 数据中心
        binding.llDataCenter.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            startPage<DataStatisticsActivity>()
        }

        // 门店设置
        binding.llStoreSettings.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            startPage<StoreSettingsActivity>()
        }

        binding.llMyWallet.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 我的钱包
            startPage<MyWalletActivity>()
        }
        binding.llEarnestMoney.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 保证金
            startPage<TeamBzActivity>()
        }

        binding.llMemberManager.clickWithTrigger {
            if (homeData?.status != "8") {
                toast("请先入驻")
                return@clickWithTrigger
            }
            // 成员管理
            startPage<MemberManagerActivity>()
        }

    }

    fun showGuide() {
        if (homeData?.status == "8" && !AccountUtils.homeGuide) {
            CurtainFlow.Builder()
                .with(1, getStepOneGuide())
                .with(2, getStepTwoGuide())
                .create()
                .start(object : CurtainFlow.CallBack {
                    override fun onProcess(currentId: Int, curtainFlow: CurtainFlowInterface?) {
                        when (currentId) {
                            1 -> {
                                curtainFlow?.findViewInCurrentCurtain<TextView>(R.id.tvNext)
                                    ?.click {
                                        curtainFlow.toCurtainById(2)
                                    }
                            }

                            2 -> {
                                curtainFlow?.findViewInCurrentCurtain<TextView>(R.id.tvNext)
                                    ?.click {
                                        AccountUtils.homeGuide = true
                                        curtainFlow.finish()
                                    }
                            }
                        }
                    }

                    override fun onFinish() {

                    }
                })
        }

    }

    private fun getStepOneGuide(): Curtain {
        return Curtain(mActivity)
            .with(binding.llStoreSettings)
            .withShape(binding.llStoreSettings, RoundShape(12f))
            .setTopView(R.layout.guide_home1)

    }

    private fun getStepTwoGuide(): Curtain {
        return Curtain(mActivity)
            .with(binding.llMemberManager)
            .withShape(binding.llMemberManager, RoundShape(12f))
            .setTopView(R.layout.guide_home2)
    }

    override fun initData() {

    }

    override fun lazyLoadData() {

        vm.getSystemConfig()

    }

    override fun onResume() {
        super.onResume()
        vm.getHomeData()
    }

    /**
     * 开始人脸识别
     * @param certifyID String
     */
    private fun verify(certifyID: String) {
        val extParams = HashMap<String, String>()
        //如需指定活体检测UI界面方向(横屏+竖屏)，请指定这一项。
        extParams.put(
            ZIMFacade.ZIM_EXT_PARAMS_KEY_SCREEN_ORIENTATION,
            ZIMFacade.ZIM_EXT_PARAMS_VAL_SCREEN_PORT
        )
        //如需支持活体视频返回，请指定这一项，并在response.videoFilePath中获取视频本地路径。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_USE_VIDEO] =
            ZIMFacade.ZIM_EXT_PARAMS_VAL_USE_VIDEO_TRUE
        //如需设置OCR的“下一步”按钮颜色（默认可不设置），请设置此项，如红色 #FF0000。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_OCR_BOTTOM_BUTTON_COLOR] = "#FF0000"
        //如需自定义活体检测页面的进度条颜色（默认可不设置），请设置此项，如红色 #FF0000。
        extParams[ZIMFacade.ZIM_EXT_PARAMS_KEY_FACE_PROGRESS_COLOR] = "#FF0000"
        val zimFacade = ZIMFacadeBuilder.create(mActivity)
        zimFacade.verify(certifyID, true, extParams) { response ->
            if (1000 == response.code) {
                toast("认证成功")
                vm.faceRecognitionCallback()
            } else {
                toast("认证失败${response.code}")
                LogUtil.debugInfo("认证失败${response.code}")
            }
            true
        }
    }

    override fun startObserve() {

        // 刷新数据
        LiveEventBus.get(RefreshHomeData::class.java).observe(this) {
            isShowing = true
            vm.getHomeData()
        }

        vm.getFaceParamsData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                verify(it?.data?.certifyId ?: "")
            }
        }

        vm.faceRecognitionCallbackData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                startPage<AgreementActivity>()
                LiveEventBus.get(RefreshTeamUserInfo::class.java).post(RefreshTeamUserInfo)
                vm.getHomeData()
            }
        }

        vm.getSystemConfigData.observeState(this) {
            onSuccess { MyApp.systemConfig = it?.data }
        }

        vm.getHomeDataData.observeState(this) {
            onError { code, msg ->
                toast(msg)
                binding.refreshLayout.finishRefresh()
            }
            onSuccess {
                binding.refreshLayout.finishRefresh()
                homeData = it?.data
                setupData()
            }
        }

        vm.checkStoreLicenseData.observeState(this) {
            onError { code, msg ->
                // 未上传营业执照
                XPopup.Builder(mActivity)
                    .asCustom(BusinessLicenseDialog(mActivity) {
                        startPage<UploadBusinessLicenseActivity>()
                    })
                    .show()
            }
        }
    }

    /**
     * 设置首页数据
     */
    private fun setupData() {
        val currentDate = Date().toDateForm("yyyy/MM/dd")
        binding.rivHead.load(homeData?.avatar)
        binding.tvName.text = homeData?.nickname
        binding.tvTime.text = currentDate
        // 总收入
        binding.tvTotalIncome.text = homeData?.total_income ?: "0.0"
        // 订单数
        binding.tvOrderNum.text = homeData?.order_total ?: "0"
        // 积分
        binding.tvIntegral.text = AccountUtils.user?.team?.team_integral ?: "0"
        // 总营业额
        binding.tvTurnover.text = homeData?.order_total_amount ?: "0.0"
        // 订单数量
        binding.llServiceOrder.visibleOrGone(homeData?.status == "8")
        // 待抢单数量
        binding.tvPendingOrders.text = homeData?.take_order_count ?: "0"
        // 待服务订单
        binding.tvUnserviced.text = homeData?.service_order_count ?: "0"
        // 进行中订单
        binding.tvInProgress.text = homeData?.work_order_count ?: "0"
        // 返工单
        binding.tvReturnOrder.text = homeData?.rework_order_count ?: "0"
        // 退款售后
        binding.tvAfterSales.text = homeData?.refund_order_count ?: "0"

        // 门店状态
        binding.llStoreState.visibleOrGone(homeData?.status != "8")

        // 获取门店是否上传营业执照
        if (homeData?.status == "8") {
            vm.checkStoreLicense()
        }

        when (homeData?.status) {
            "-1" -> {
                // 未入驻
                binding.tvStoreState.text = "门店状态: 未入驻"
                binding.tvStoreStateDescription.text = "当前门店状态未入驻, 请填写资料进行入驻"
                // 显示联系管家
                binding.tvContactButler.visibleOrGone(true)
                // 显示门店入驻
                binding.tvConfirm.visibleOrGone(true)
                binding.tvConfirm.text = "去入驻"
            }

            "0" -> {
                // 待审核
                binding.tvStoreState.text = "门店状态: 待审核"
                binding.tvStoreStateDescription.text = "当前门店状态待审核, 如有疑问请联系管家"
                binding.tvContactButler.visibleOrGone(false)
                binding.tvConfirm.visibleOrGone(true)
                binding.tvConfirm.text = "联系管家"
            }

            "2" -> {
                // 审核未通过
                binding.tvStoreState.text = "门店状态: 已拒绝"
                binding.tvStoreStateDescription.text = "当前门店状态被拒绝, ${homeData?.fail_msg}"
                binding.tvContactButler.visibleOrGone(false)
                binding.tvConfirm.visibleOrGone(true)
                binding.tvConfirm.text = "重新认证"
            }

            "3" -> {
                // 未人脸
                binding.tvStoreState.text = "门店状态: 识别认证"
                binding.tvStoreStateDescription.text = "当前门店状态为未实名, 请前往进行人脸识别"
                binding.tvContactButler.visibleOrGone(false)
                binding.tvConfirm.visibleOrGone(true)
                binding.tvConfirm.text = "去认证"
            }

            "5" -> {
                // 未签署合同
                binding.tvStoreState.text = "门店状态: 签署合同"
                binding.tvStoreStateDescription.text = "当前门店状态为未签合同, 请前往签署合同"
                binding.tvContactButler.visibleOrGone(false)
                binding.tvConfirm.visibleOrGone(true)
                binding.tvConfirm.text = "去签署"
            }

            "7" -> {
                // 未交费
                binding.tvStoreState.text = "门店状态: 支付合作费用"
                binding.tvStoreStateDescription.text =
                    "当前门店状态为未支付费用, 请前往进行支付费用"
                binding.tvContactButler.visibleOrGone(false)
                binding.tvConfirm.visibleOrGone(true)
                binding.tvConfirm.text = "立即支付"
            }

            "9" -> {
                // 后台录入
                binding.tvStoreState.text = "门店状态: 确认资料"
                binding.tvStoreStateDescription.text =
                    "管家已经完成资料录入, 请前往确认资料并提交审核"
                binding.tvContactButler.visibleOrGone(false)
                binding.tvConfirm.visibleOrGone(true)
                binding.tvConfirm.text = "查看资料"
            }
        }

        noticeList.clear()
        noticeList.addAll(homeData?.sys_notice ?: listOf())
        binding.marqueeView.startWithList(noticeList.map { it.title })
        binding.llNotice.visibleOrGone(noticeList.isNotEmpty())
    }

}